<?php

namespace Users\Recover;

use Pinenut\Form;
use Pinenut\User\Auth\EmailPassword;
use Pinenut\Mail;
use EmailDelivery\EmailDelivery;

class GenerateCodeAction extends \Action {
	protected static $isPublic = true;
	
	protected static $layout = "#layouts.column1Narrow";
	
	protected static $config = 'Users\Recover\GenerateCodeFormConfig';
	
	function privileges() {
		return '#unauthorized';
	}
	
	/**
	 * Указываем необходимые неявные параметры
	 * @return multitype:string
	 */
	static function pullParams() {
		return ['sessionId', 'isPost', 'isAjax'];
	}
	
	public function run() {
		
		// отрубаем кеширование если пост-запрос
		if ($this->request->_isPost) {
			$this->response->noCache(true);
		}
		
		$conf = static::$config;
		
		$formConfig = $conf::get();
		
		$form = new Form($this->request->_sessionId, 'generateCode', $formConfig);

		if ($this->request->_isPost && $this->request->_isAjax) {
			$form->process($this->request->params(), true);
			$this->response->content = $form->render();
			$this->response->noRender(true);
			return;
		} else if ($this->request->_isPost && !$this->request->onlyRender) {
			if (!$form->process($this->request->params())) {
				$this->response->form = $form;
				return;
			}

			$code = EmailPassword::generateRecoveryCode($this->request->email);

			EmailDelivery::sendTemplate(
				\EmailDeliveryConfig::TEMPLATE_TYPE_RECOVERY, 
				[
					'email' => $this->request->email,
					'code' => $code
				]
			);
			
			$this->redirect($this->url('users.recover.checkCode'));
			
			return;
		}

		$this->response->form = $form;
	}

}
